package cn.i96688.scanclient.barcode;

import cn.i96688.scanclient.bean.PayLog;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser.HHOOK;
import com.sun.jna.platform.win32.WinUser.KBDLLHOOKSTRUCT;
import com.sun.jna.platform.win32.WinUser.LowLevelKeyboardProc;
import com.sun.jna.platform.win32.WinUser.MSG;

public class ScanBarcodeService {
    private HHOOK hhkKeyBoard;
    private final User32 lib = User32.INSTANCE;
    

    public void stopScanBarcodeService() {    
        lib.UnhookWindowsHookEx(hhkKeyBoard);    
    }

    public void startScanBarcodeService() {
        final BarcodeKeyboardListener listener=new BarcodeKeyboardListener();
        LowLevelKeyboardProc keyboardHook = new LowLevelKeyboardProc() {

            @Override
            public LRESULT callback(int nCode, WPARAM wParam,
                    KBDLLHOOKSTRUCT info) {
                if (nCode >= 0) {
                    switch (wParam.intValue()) {
                        case WinUser.WM_KEYUP:
                            int keyCode = info.vkCode;
                            
                            if (keyCode >= 48 && keyCode <= 57) {
                                listener.onKey(keyCode);
                            }
                            if (keyCode == 13) {
                                listener.onKey(keyCode);
                            }
                            break;
                         default:
                        	 break;
                    }
                }
                return lib.CallNextHookEx(hhkKeyBoard, nCode, wParam,null);
            }
        };
        
        HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
        
        hhkKeyBoard = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
        
        int result;
        MSG msg = new MSG();
        while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
                if (result == -1) {
                	PayLog.getInstance().addLog("读取条码信息出错");
                    break;
                } else {
                    lib.TranslateMessage(msg);
                    lib.DispatchMessage(msg);
                }
        }
    }
}
